package com.xie.authority_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xie.authority_system.entity.Department;
import com.xie.authority_system.service.DepartmentService;
import com.xie.authority_system.utils.Result;
import com.xie.authority_system.vo.query.DepartmentQueryVo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 谢金成
 * @date 2024/1/8 14:57
 */
@RestController
@RequestMapping("/api/department")
public class DepartmentController {

    @Resource
    private DepartmentService departmentService;

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:department:select')")
    public Result list(DepartmentQueryVo departmentQueryVo) {
        // 调用查询部门列表方法
        List<Department> departmentList = departmentService.findDepartmentList(departmentQueryVo);

        return Result.ok(departmentList);
    }

    @GetMapping("/parent/list")
    @PreAuthorize("hasAuthority('sys:department:select')")
    public Result getParentDepartment() {
        List<Department> departmentList = departmentService.findParentDepartment();

        return Result.ok(departmentList);
    }

    /**
     * 添加部门
     *
     * @param department
     * @return
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:department:add')")
    public Result add(@RequestBody Department department) {
        if (departmentService.save(department)) {
            return Result.ok().message("部门添加成功");
        }

        return Result.error().message("部门添加失败");
    }

    /**
     * 修改部门
     *
     * @param department
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:department:edit')")
    public Result update(@RequestBody Department department) {
        if (departmentService.updateById(department)) {
            return Result.ok().message("部门修改成功");
        }

        return Result.error().message("部门修改失败");
    }

    /**
     * 检查是否有子部门
     *
     * @param id
     * @return
     */
    @GetMapping("/check/{id}")
    @PreAuthorize("hasAuthority('sys:department:delete')")
    public Result check(@PathVariable Long id) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", id);
        // 判断数量是否大于0
        if (departmentService.count(queryWrapper) > 0) {
            return Result.exist().message("该部门下存在子部门, 无法删除");
        }
        return Result.ok();
    }

    /**
     * 删除失败
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:department:delete')")
    public Result delete(@PathVariable Long id) {
        if (departmentService.removeById(id)) {
            return Result.ok().message("部门删除成功");
        }

        return Result.error().message("部门删除失败");
    }
}
